/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: ForgetPasswdActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import io.bhex.app.utils.SkinColorUtil;
import io.bhex.baselib.constant.AppData;
import io.bhex.sdk.account.bean.FindPwdCheckResponse;
import io.bhex.app.R;
import io.bhex.sdk.account.bean.MobileCodeListBean;
import io.bhex.app.account.presenter.ForgetPasswdPresenter;
import io.bhex.app.base.BaseActivity;
import io.bhex.baselib.constant.Fields;
import io.bhex.app.safe.DeepKnowVerify;
import io.bhex.app.safe.DeepSEListener;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.app.view.InputView;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;


public class ForgetPasswdActivity extends BaseActivity<ForgetPasswdPresenter,ForgetPasswdPresenter.ForgetPasswdUI> implements ForgetPasswdPresenter.ForgetPasswdUI, View.OnClickListener, TextWatcher {

    private static final int VERIFY_REQUEST_CODE = 0x17;
    private TopBar topBar;
    private Button btnNext;
    private InputView accountEt;
    private InputView verifyEt;
    private boolean isEmail=true;
    private TextView mobileCodeTx;
    private TextView sendVerifyCodeTv;
    private DeepKnowVerify deepKnowVerify;

    @Override
    protected int getContentView() {
        return R.layout.activity_forget_passwd_layout;
    }

    @Override
    protected ForgetPasswdPresenter createPresenter() {
        return new ForgetPasswdPresenter();
    }

    @Override
    protected ForgetPasswdPresenter.ForgetPasswdUI getUI() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置禁止系统截屏、录制
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
    }

    @Override
    protected void initView() {
        super.initView();
        deepKnowVerify = DeepKnowVerify.getInstance(this);
        topBar = viewFinder.find(R.id.topBar);
        topBar.setLeftImg(R.mipmap.btn_head_back);
        topBar.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        Intent intent = getIntent();
        if (intent != null) {
            isEmail = intent.getBooleanExtra("isEmail",true);
        }

        if (isEmail) {
            viewFinder.find(R.id.mobile_code_linear).setVisibility(View.GONE);
        }else{
            viewFinder.find(R.id.mobile_code_linear).setVisibility(View.VISIBLE);
        }

        sendVerifyCodeTv =  viewFinder.textView(R.id.get_verify_code);
        mobileCodeTx =  viewFinder.textView(R.id.mobile_code);
        btnNext = viewFinder.find(R.id.btn_nextstep);
        accountEt = viewFinder.find(R.id.account_et);
        accountEt.setPaddingLeft(PixelUtils.dp2px(isEmail?8:68));
        accountEt.setInputHint(isEmail?getString(R.string.enter_email):getString(R.string.enter_phone_number));
        accountEt.setInputMode(InputView.SILENTMODE);
        verifyEt = viewFinder.find(R.id.verify_code_et);
        verifyEt.setPaddingRight(PixelUtils.dp2px(80));
        verifyEt.setInputHint(getString(R.string.enter_verify));
        verifyEt.setInputMode(InputView.SILENTMODE);

        setDefaultMobileCode();

    }

    private void setDefaultMobileCode() {
        String defaultMobileCode = CommonUtil.getDefaultMobileCode(this);
        if (!TextUtils.isEmpty(defaultMobileCode)) {
            mobileCodeTx.setText("+"+defaultMobileCode);
        }
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.mobile_code_linear).setOnClickListener(this);
        viewFinder.find(R.id.btn_nextstep).setOnClickListener(this);
        viewFinder.find(R.id.get_verify_code).setOnClickListener(this);
        deepKnowVerify.ignoreDPView(viewFinder.find(R.id.get_verify_code),"ForgetPasswdActivity");
        accountEt.addTextWatch(this);
        verifyEt.addTextWatch(this);
    }


    @Override
    public void setAuthTv(String s) {
        sendVerifyCodeTv.setText(s);
    }

    @Override
    public boolean isChinaMobile() {
        return !isEmail && mobileCodeTx.getText().toString().equals("+86");
    }

    @Override
    public void setAuthTvStatus(boolean b) {
        sendVerifyCodeTv.setEnabled(b);
        sendVerifyCodeTv.setTextColor(b ? getResources().getColor(R.color.blue) : SkinColorUtil.getDark50(this));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.mobile_code_linear:
                //选择国家区号
                IntentUtils.goMobileCodeList(this, Fields.REQUEST_CODE_FIND, Fields.FIELD_COUNTRY_PARAM_TYPE_AREA_CODE);
                 break;
            case R.id.get_verify_code:
                final String account = accountEt.getInputString();
                if (TextUtils.isEmpty(account)) {
                    ToastUtils.showShort(this, isEmail?getResources().getString(R.string.input_email):getResources().getString(R.string.input_phone_number));
//                    accountEt.setError(isEmail?getResources().getString(R.string.input_email):getResources().getString(R.string.input_phone_number));
                    return;
                }else{
                    accountEt.setError("");
                }
                if (!NetWorkStatus.isConnected(this)) {
                    ToastUtils.showShort(this, getResources().getString(R.string.hint_network_not_connect));
                    return;
                }
                getUI().showProgressDialog("","");
                deepKnowVerify.verify(baseSEListener);
                 break;
            case R.id.btn_nextstep:
                getPresenter().findPasswdCheck(isEmail,mobileCodeTx.getText().toString().replace("+", ""),accountEt,verifyEt);
                break;
        }
    }


    private DeepSEListener baseSEListener = new DeepSEListener() {

        /**
         * SDK内部show loading dialog
         */
        @Override
        public void onShowDialog() {
            getUI().dismissProgressDialog();
        }

        @Override
        public void onError(String errorCode, String error) {
//            DebugLog.i(TAG,"onError-->errorCode:"+errorCode+", error: "+error);
//            ToastUtils.showShort(error);
            getUI().dismissProgressDialog();
            ToastUtils.showShort(getString(R.string.string_net_exception)+errorCode);
        }

        /**
         * 验证码Dialog关闭
         * 1：webview的叉按钮关闭
         * 2：点击屏幕外关闭
         * 3：点击回退键关闭
         *
         * @param num
         */
        @Override
        public void onCloseDialog(int num) {
//            DebugLog.i(TAG, "onCloseDialog-->" + num);
        }

        /**
         * show 验证码webview
         */
        @Override
        public void onDialogReady() {
            //RateAndLocalManager.GetInstance(ForgetPasswdActivity.this).SetCurLocalKind(RateAndLocalManager.GetInstance(ForgetPasswdActivity.this).getCurLocalKind());

//            DebugLog.i(TAG,"onDialogReady-->SDK show captcha webview dialog! ");
        }

        /**
         * 验证成功
         * @param token
         */
        @Override
        public void onResult(String token) {
//            DebugLog.i(TAG,"onResult: "+token);
            //去二次验证
            getPresenter().verifyFirstRequest(isEmail,mobileCodeTx.getText().toString().replace("+", ""),accountEt,token);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        deepKnowVerify.destroy();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        checkEditText();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private void checkEditText() {
        String account = accountEt.getInputString();
        String verifyCode = verifyEt.getInputString();
        if (TextUtils.isEmpty(account)||TextUtils.isEmpty(verifyCode)){
            btnNext.setEnabled(false);
        }else{
            btnNext.setEnabled(true);
        }
    }

    /**
     * 下一步校验成功，跳转到设置密码
     * @param isEmail
     * @param account
     * @param nationalCode
     * @param findPwdCheckResponse
     */
    @Override
    public void checkSuccess(boolean isEmail, String account, String nationalCode, FindPwdCheckResponse findPwdCheckResponse) {
        if (findPwdCheckResponse != null) {
            if (findPwdCheckResponse.isNeed2FA()) {
                IntentUtils.goFindPwdTwoVerify(this, AppData.INTENT.REQUEST_CODE_FIND_PWD_2FA,isEmail,account,nationalCode,findPwdCheckResponse);
            }else{
                String requestId = findPwdCheckResponse.getRequestId();
                if (!TextUtils.isEmpty(requestId)) {
                    IntentUtils.goFindPasswd(this,isEmail,account,nationalCode,requestId);
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Fields.REQUEST_CODE_FIND && resultCode == RESULT_OK) {
            MobileCodeListBean.MobileCodeBean mobileCodeBean = (MobileCodeListBean.MobileCodeBean) data.getSerializableExtra(Fields.INTENT_MOBILE_CODE);
            if (mobileCodeBean != null) {
                String countryCode = mobileCodeBean.getNationalCode();
                if (!TextUtils.isEmpty(countryCode)) {
                    mobileCodeTx.setText("+" + countryCode);
                }
            }
        }else if(requestCode == VERIFY_REQUEST_CODE && resultCode == RESULT_OK){
            if (data != null) {
                String token = data.getStringExtra("token");

                getPresenter().verifyFirstRequest(isEmail,mobileCodeTx.getText().toString().replace("+", ""),accountEt,token);
            }
        }
    }
}
